"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 多节点写入
Case Name   : 备机开启事务执行lock table和truncate table，不支持，合理报错
Create At   : 2023/07/20
Owner       : opentestcase033
Description :
    1.修改enable_remote_execute参数值为on
    2.创建测试表
    3.备节点开启事务执行lock table
    4.备节点事务内执行truncate table
    5.清理环境
Expect      :
    1.修改成功
    2.执行成功
    3.报错
    4.报错
    5.成功
History     :
    modified: 2025/03/05 modified by kyleze,参数值变化,优化用例
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == PrimarySh.get_node_num(),
                 'Single node, and subsequent codes are not executed.')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.standby_node = Node('Standby1DbUser')
        self.standby_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.common = Common('Standby1DbUser')
        self.table = 't_multi_node_write_0073'
        self.enable_remote_execute = 'enable_remote_execute'
        self.remote_excute_default = self.common.show_param(
            self.enable_remote_execute)

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, f'执行失败:{step1}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, f'执行失败:{step1}')
        show_remote_excute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_excute, 'on', f'执行失败:{step1}')

        step2 = "-----step2:创建测试表;expect:执行成功-----"
        self.logger.info(step2)
        sql_cmd = f'''drop table if exists {self.table};
            create table {self.table}(
            id int, name varchar, source number) with (segment=on);
            insert into {self.table} values (1,'haha',92);;'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS,
                      sql_msg, f'执行失败:{step2}')
        time.sleep(2)

        step3 = "-----step3:备节点开启事务执行lock table;expect:报错，回滚-----"
        self.logger.info(step3)
        sql_cmd = f'''begin;
        lock table {self.table};
        select locktype, mode, granted, fastpath from pg_locks where 
        relation = (select oid from pg_class where relname='{self.table}');
        end;'''
        sql_msg = self.standby_sh.execut_db_sql(sql_cmd)
        self.logger.info(sql_msg)
        msg = "ERROR:  The multi-write feature doesn't support " \
              "DDL within transaction!"
        self.assertIn(msg, sql_msg, f'执行失败:{step3}')
        self.assertIn('ERROR:  current transaction is aborted',
                      sql_msg, f'执行失败:{step3}')
        self.assertIn(self.constant.ROLLBACK_MSG, sql_msg, f'执行失败:{step3}')

        step4 = "-----step4:备节点事务内执行truncate table;expect:报错，回滚-----"
        self.logger.info(step4)
        sql_msg = self.standby_sh.execut_db_sql(
            f"start transaction;truncate table {self.table};end;")
        self.logger.info(sql_msg)
        self.assertIn(msg, sql_msg, f'执行失败:{step4}')
        self.assertIn(self.constant.ROLLBACK_MSG, sql_msg, f'执行失败:{step4}')

    def tearDown(self):
        step5 = "-----step5:恢复参数;expect:恢复参数成功-----"
        self.logger.info(step5)
        drop_res = self.standby_sh.execut_db_sql(
            f"drop table if exists {self.table} cascade;")
        self.logger.info(drop_res)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_excute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, drop_res,
                      f'执行失败:{step5}')
        self.assertTrue(result, f'执行失败:{step5}')
        self.assertTrue(restart_res, f'执行失败:{step5}')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
